const vscode = require('vscode');
const { callQwen } = require('../utils/utils.js');

async function addCommentToLines(editor, selection) {
    const document = editor.document;
    const lines = selection ? 
        document.getText(selection).split('\n') :
        Array.from({length: document.lineCount}, (_, i) => document.lineAt(i).text);

/*     const messageObj = {
        message:lines,
        model: "qwen-coder-plus-latest"
    }; */

    try {
        // 获取AI生成的注释
        const response = await callQwen(lines);
        
        // 将响应按行分割成注释数组
        const comments = response.split('\n').map(line => line.trim());
        
        // 添加注释到代码中
        return editor.edit(editBuilder => {
            const startLine = selection ? document.positionAt(document.offsetAt(selection.start)).line : 0;
            
            lines.forEach((line, index) => {
                const currentLine = startLine + index;
                const lineText = selection ? line : document.lineAt(currentLine).text;
                
                if (lineText.trim() !== '') {
                    const position = new vscode.Position(currentLine, lineText.length);
                    // 使用对应的注释，如果没有对应注释则使用空字符串
                    editBuilder.insert(position, `  ${comments[index] || ''}`);
                }
            });
        });
    } catch (error) {
        vscode.window.showErrorMessage('生成注释失败：' + error.message);
    }
}

function registerAddCommentCommand(context) {
    let disposable = vscode.commands.registerCommand('gptdemo.addComment', () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            const selection = editor.selection;
            if (!selection.isEmpty) {
                addCommentToLines(editor, selection);
            } else {
                addCommentToLines(editor, null);
            }
        }
    });

    context.subscriptions.push(disposable);
}

module.exports = registerAddCommentCommand;